package com.share.domain.strategy.service.rule.chain.impl;

import com.share.domain.strategy.repository.IStrategyRepository;
import com.share.domain.strategy.service.armory.IStrategyDispatch;
import com.share.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.share.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.share.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 权重方法责任链节点
 */
@Component("rule_weight")
@Slf4j
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    @Resource
    private IStrategyDispatch strategyDispatch;




    @Override
    public DefaultChainFactory.StrategyAwardVo logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重处理：userId：{}，ruleModel：{}",userId,ruleModel());
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());
        Map<Long, String> analyticalValueGroup = getAnalyticalValue(ruleValue);

        //规则配置为空，跳过本次责任节点
        if(null==analyticalValueGroup||analyticalValueGroup.isEmpty())return null;

        List<Long> analyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());
        Collections.sort(analyticalSortedKeys);

        //查询总使用次数
        Integer userScore = repository.queryActivityAccountTotalUserCount(userId,strategyId);
        Long nextValue = analyticalSortedKeys.stream()
                .filter(key->userScore>=key)
                .max(Long::compareTo)
                .orElse(null);
        if(null!=nextValue){
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValueGroup.get(nextValue));
            log.info("抽奖责任链-权重接管：userId：{}，ruleModel：{},awardId:{}",userId,ruleModel(),awardId);
            return DefaultChainFactory.StrategyAwardVo.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }
        log.info("抽奖责任链-权重放行：userId：{}，ruleModel：{}",userId,ruleModel());
        return next().logic(userId,strategyId);

    }

    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroup = ruleValue.split(Constants.SPACE);
        Map<Long,String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleValueGroup) {
            if(ruleValueKey == null && ruleValueKey.isEmpty()){
                return ruleValueMap;
            }
            String[] parts = ruleValueKey.split(Constants.COLON);
            if(parts.length!=2){
                throw new IllegalArgumentException("rule_weigh rule_rule invalid format(非法格式):"+ruleValueKey);
            }
            ruleValueMap.put(Long.valueOf(parts[0]),ruleValueKey);
        }
        return ruleValueMap;
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }
}
